<template>
    <div class="forgot-container">
      <div class="forgot-box">
        <h2 class="forgot-title">找回密码</h2>
        
        <el-form
          ref="forgotForm"
          :model="forgotForm"
          :rules="forgotRules"
          @submit.prevent="handleSubmit"
        >
          <el-form-item prop="username">
            <el-input
              v-model="forgotForm.username"
              placeholder="请输入用户名"
              prefix-icon="User"
              size="large"
            />
          </el-form-item>
          
          <el-form-item prop="phone">
            <el-input
              v-model="forgotForm.phone"
              placeholder="请输入注册手机号"
              prefix-icon="Phone"
              size="large"
            >
              <template #append>
                <el-button 
                  :disabled="isCountingDown"
                  @click="getVerificationCode"
                >
                  {{ countdown > 0 ? `${countdown}秒后重试` : '获取验证码' }}
                </el-button>
              </template>
            </el-input>
          </el-form-item>
          
          <el-form-item prop="verificationCode">
            <el-input
              v-model="forgotForm.verificationCode"
              placeholder="请输入验证码"
              prefix-icon="Message"
              size="large"
            />
          </el-form-item>
          
          <el-form-item prop="newPassword">
            <el-input
              v-model="forgotForm.newPassword"
              type="password"
              placeholder="请输入新密码（至少8位且包含字母）"
              prefix-icon="Lock"
              size="large"
              show-password
            />
          </el-form-item>
          
          <el-form-item prop="confirmPassword">
            <el-input
              v-model="forgotForm.confirmPassword"
              type="password"
              placeholder="请确认新密码"
              prefix-icon="Lock"
              size="large"
              show-password
            />
          </el-form-item>
          
          <el-form-item>
            <el-button
              type="primary"
              size="large"
              class="submit-button"
              :loading="loading"
              native-type="submit"
            >
              重置密码
            </el-button>
          </el-form-item>
        </el-form>
        
        <div class="back-login">
          <el-link type="primary" :underline="false" @click="goToLogin">
            <el-icon><ArrowLeft /></el-icon> 返回登录
          </el-link>
        </div>
      </div>
    </div>
  </template>
  
  <script setup>
  import { ref } from 'vue'
  import { useRouter } from 'vue-router'
  import { ElMessage } from 'element-plus'
  import { ArrowLeft } from '@element-plus/icons-vue'
  import axios from 'axios'
  import { getApiUrl } from '../config/api.js'
  
  const router = useRouter()
  
  const forgotForm = ref({
    username: '',
    phone: '',
    verificationCode: '',
    newPassword: '',
    confirmPassword: ''
  })
  
  const countdown = ref(0)
  const isCountingDown = ref(false)
  const loading = ref(false)
  
  // 密码验证规则
  const validatePassword = (rule, value, callback) => {
    if (!value) {
      callback(new Error('请输入新密码'))
    } else if (value.length < 8) {
      callback(new Error('密码长度不能小于8位'))
    } else if (!/[a-zA-Z]/.test(value)) {
      callback(new Error('密码必须包含至少一个字母'))
    } else {
      if (forgotForm.value.confirmPassword !== '') {
        forgotFormRef.value.validateField('confirmPassword')
      }
      callback()
    }
  }
  
  const validateConfirmPassword = (rule, value, callback) => {
    if (!value) {
      callback(new Error('请再次输入密码'))
    } else if (value !== forgotForm.value.newPassword) {
      callback(new Error('两次输入密码不一致!'))
    } else {
      callback()
    }
  }
  
  const forgotRules = {
    username: [
      { required: true, message: '请输入用户名', trigger: 'blur' },
      { min: 4, message: '用户名长度不能小于4个字符', trigger: 'blur' }
    ],
    phone: [
      { required: true, message: '请输入手机号', trigger: 'blur' },
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
    ],
    verificationCode: [
      { required: true, message: '请输入验证码', trigger: 'blur' },
      { pattern: /^\d{6}$/, message: '验证码为6位数字', trigger: 'blur' }
    ],
    newPassword: [
      { required: true, validator: validatePassword, trigger: 'blur' }
    ],
    confirmPassword: [
      { required: true, validator: validateConfirmPassword, trigger: 'blur' }
    ]
  }
  
  // 获取验证码
  const getVerificationCode = async () => {
    if (!forgotForm.value.username) {
      ElMessage.warning('请输入用户名')
      return
    }
    
    if (!forgotForm.value.phone) {
      ElMessage.warning('请输入手机号')
      return
    }
    
    try {
      const response = await axios.post(getApiUrl('/auth/send-verification-code'), {
        username: forgotForm.value.username,
        phone: forgotForm.value.phone
      })
      
      isCountingDown.value = true
      countdown.value = 60
      
      const timer = setInterval(() => {
        countdown.value--
        if (countdown.value <= 0) {
          clearInterval(timer)
          isCountingDown.value = false
        }
      }, 1000)
      
      ElMessage.success('验证码已发送到您的手机')
    } catch (error) {
      ElMessage.error(error.response?.data || '发送验证码失败')
    }
  }
  
  // 提交重置密码
  const handleSubmit = async () => {
    loading.value = true
    
    try {
      const response = await axios.post(getApiUrl('/auth/reset-password'), {
        username: forgotForm.value.username,
        phone: forgotForm.value.phone,
        verificationCode: forgotForm.value.verificationCode,
        newPassword: forgotForm.value.newPassword
      })
      
      loading.value = false
      ElMessage.success('密码重置成功！即将跳转到登录页面')
      
      // 2秒后跳转到登录页
      setTimeout(() => {
        router.push('/')
      }, 2000)
    } catch (error) {
      loading.value = false
      ElMessage.error(error.response?.data || '密码重置失败')
    }
  }
  
  // 返回登录页
  const goToLogin = () => {
    router.push('/')
  }
  </script>
  
  <style scoped>
  .forgot-container {
    width: 100%;
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  
  .forgot-box {
    width: 500px;
    padding: 350px;
    border-radius: 12px;
  }
  
  .forgot-title {
    text-align: center;
    margin-bottom: 40px;
    font-size: 24px;
    font-weight: 600;
  }
  
  .submit-button {
    width: 100%;
    font-size: 16px;
    height: 48px;
    margin-top: 10px;
  }
  
  .back-login {
    text-align: center;
    margin-top: 20px;
  }
  
  .back-login .el-link {
    display: inline-flex;
    align-items: center;
  }
  </style>